package us.gaaoc.framework.webapp.filter;

import java.io.File;
import java.io.IOException;
import java.io.Writer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileSystemUtils;

/**
 * This is a filter which checks the health of the server and the running JVM.
 * 
 * @author artripa
 * 
 */
public class ServerHealthFilter implements Filter {

	@Override
	public void destroy() {

	}
		
	
	
	protected void serverDownMessage(ServletRequest req, ServletResponse resp,String message) throws IOException
	{
		
		resp.setContentType("text/html");		
		((HttpServletResponse)resp).sendError(503);
		Writer wr = resp.getWriter();
		
		wr.write("<html>");
		wr.write("<head></head>");
		
		wr.write("<body>");
		
		wr.write("<p>There is a system error with GAJE 2.0. This error has been generated " +
				"to prevent invalid case data from being created " +
				"with the case system." +
				"</p>");
		
		wr.write("<p>Notify the GAAOC of this error</p>");
		
		wr.write("<p> Error Messages: </p>");
		
		for(String l : message.split("\n"))
		{
			wr.write("<p>");
			wr.write(l);
			wr.write("</p>");
		}		
		wr.write("</body>");
		wr.write("</html>");		
		
		wr.close();
		wr.flush();
		
	}
	
	
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {

		boolean serverDown = false;		
		String message = "";
		
		// if the free filespace is less 200MB then we PANIC!
		if (FileSystemUtils.freeSpaceKb("/") < 1638400) {			
			serverDown = true;
			message += "File System / has no space left\n";
		}

		// if the free filespace is less 200MB then we PANIC!
		if (FileSystemUtils.freeSpaceKb("/home/") < 1638400) {
			serverDown = true;
			message += "File System /home has no space left\n";
		}

		// if the free filespace is less 200MB then we PANIC!
		if (FileSystemUtils.freeSpaceKb("C:" + File.separator + "temp" + File.separator) < 1638400) {
			serverDown = true;		
			message += "File System /srv/documents has no space left\n";
		}
		
		if (new File("/srv/gaje/downtime").exists())
		{
			serverDown = true;
			message += "A test message 1\n";
			message += "A test message 2\n";
			message += "A test message 3\n";
		}
				
		if(serverDown) {
			serverDownMessage(req,resp,message);
			return;
		}else{
			chain.doFilter(req,resp);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
